package com.nextbusmn.server.JDOWrappers;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;
import com.nextbusmn.server.dataobjects.BusStopData;
import com.nextbusmn.server.dataobjects.NextBusData;
import com.nextbusmn.server.dataobjects.StopTimeData;


// wrapper for storing/deleting/updating BusStopData objects
public class BusStopJDOWrapper extends JDOWrapper {

	public BusStopJDOWrapper(BusStopData data) {
		this.setData(data);
	}
	
	@Override
	public boolean dataExists(NextBusData data) {
		BusStopData id = getByStopID(((BusStopData) data).getStopID());
		return id != null;
	}
	
	public static BusStopData getByID(String agencyID) {
		PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
		return (BusStopData) pm.getObjectById(BusStopData.class, agencyID);
	}
	
	public static BusStopData getByStopID(int ID) {
		PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
		
		Query query = pm.newQuery(BusStopData.class);
		query.setFilter("stopID == IDParam");
		query.declareParameters("int IDParam");

		List<BusStopData> result = null;
		
		try {
			result = (List<BusStopData>) query.execute(ID);
		} finally {
			query.closeAll();
		}
		
		if (result.size() > 1) {
			System.out.println("Data problem: Key not unique!"); 
		}
		
		return result.size() == 1 ? result.get(0) : null;
	}
	
	public static List<BusStopData> getStopsByStopIDs(Set<Integer> stopIDs) {
		PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
		
		List<BusStopData> finalList = new ArrayList<BusStopData>();
		
		Query query = pm.newQuery(BusStopData.class);
		
		for (int sID : stopIDs) {
			query.setFilter("stopID == paramID");
			query.declareParameters("int paramID");
			
			List<BusStopData> result = null;
			
			try {
				result = (List<BusStopData>) query.execute(sID);
			} finally {
				query.closeAll();
			}
			
			finalList.addAll(result);
		}
		
		return finalList;
	}
	
	public static List<BusStopData> getAllRows() {
		return (List<BusStopData>) JDOWrapper.getAllRows(BusStopData.class);
	}

	public static List<BusStopData> getAllRowsForUpdate() {
		PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
		
		List<BusStopData> finalList = new ArrayList<BusStopData>();
		List<BusStopData> result = new ArrayList<BusStopData>();
		
		Query query = pm.newQuery(BusStopData.class);
		
		try {
			result = (List<BusStopData>) query.execute();
			finalList = (List<BusStopData>) pm.detachCopyAll(result);
		} finally {
			query.closeAll();
		}
		
		return finalList;
	}

	public static void update(BusStopData bsd) {
		PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
		try {
            pm.makePersistent(bsd);
        } finally {
            pm.close();
        }

	}
	
}
